<?php
date_default_timezone_set("Asia/Shanghai");
//require_once __DIR__ . '/vendor/autoload.php';
include __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/HuishengMysql.php';
require_once __DIR__ . '/HuishengRedis.php';
require_once __DIR__ . '/CaptureFileHandler.php';
require_once __DIR__ . '/RolesSeparation.php';
require_once __DIR__ . '/UploadFileHandler.php';
use Workerman\Worker;
use Workerman\Lib\Timer;

$worker = new Worker();

$worker->onWorkerStart = function () {
    $config = require __DIR__ . '/config.php';
    $db = new HuishengMysql($config['mysql']);
    $capture = Timer::add(10, "MacCaptureFileEntry", array($db));
    //$upload = Timer::add(10, "UploadFileEntry", array($db));
};

function MacCaptureFileEntry($db)
{
    $fp = fopen(__DIR__ . "/keys/" . md5('Capture_file'), 'w+');
    if (!flock($fp, LOCK_EX | LOCK_NB)) {
        return;
    }
    $captureFileHandler = new CaptureFileHandler($db);
    MacCaptureFileHandle($captureFileHandler);
    flock($fp, LOCK_UN);
    fclose($fp);
}

function MacCaptureFileHandle($captureFileHandler)
{
    $config = require __DIR__ . '/config.php';
    $fileGroup = CaptureFileHandler::listAllFiles($config['share_path'] . $config['queuedir']);
    foreach ($fileGroup as $file) {
        $captureFileHandler->CaptureFileHandle($file);
        CaptureFilePop($file);
    }
}

function CaptureFilePop($filepath){
    unlink($filepath);
}

function UploadFileEntry($db)
{
    $fp = fopen(__DIR__ . "/keys/" . md5('Upload_file'), 'w+');
    if (!flock($fp, LOCK_EX | LOCK_NB)) {
        return;
    }
    $uploadFileHandler = new UploadFileHandler($db);
    UsbUploadFileHandler($uploadFileHandler);
    flock($fp, LOCK_UN);
    fclose($fp);
}

function UsbUploadFileHandler($handler){
    while(($file_attr = FilePopFromList())){
        $attr = new VADFileAttr($file_attr);
        $operat = new AudioFileAllOperation();
        $handler->uploadFileHandle($attr, $operat); 
        //isSeparatRoles($attr->getVadPath());
    }
}


function FilePopFromList(){
    $config = require __DIR__ . '/config.php';
    $redis = new HuishengRedis($config['redis']);
    $data = $redis->uploadFilePop();
    return json_decode($data, true);
}

if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}
